<template>
  <!-- 面包屑 -->
  <Breadcrumb />
  <el-button type="primary" @click="setFlag">添加商品</el-button>
  <el-table :data="shopList.slice((currentPage4-1)*pageSize4,currentPage4*pageSize4)" style="width: 100%">
    <el-table-column prop="name" label="商品名称" />
    <el-table-column prop="category_name" label="商品分类" />
    <el-table-column label="商品图片">
      <template #default="scope">
        <div class="demo-image__preview">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.img_path"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :initial-index="4"
            fit="cover"
            z-index="1000"
          />
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="price" label="价格" width="80" />
    <el-table-column prop="repertory" label="库存" width="80" />
    <el-table-column prop="market" label="市场价" width="80" />
    <el-table-column label="是否热销单品">
      <template #default="scope">
        <el-switch
          :active-value="1"
          :inactive-value="2"
          v-model="scope.row.is_danpin"
          class="ml-2"
          @change="setDan(scope.row.id, $event)"
        />
      </template>
    </el-table-column>
    <el-table-column label="是否今日上新">
      <template #default="scope">
        <el-switch
          :active-value="1"
          :inactive-value="2"
          v-model="scope.row.is_shangxin"
          class="ml-2"
          @change="setShangXin(scope.row.id, $event)"
        />
      </template>
    </el-table-column>
    <el-table-column label="是否精品优选">
      <template #default="scope">
        <el-switch
          :active-value="1"
          :inactive-value="2"
          v-model="scope.row.is_jingxuan"
          class="ml-2"
          @change="setJingXuan(scope.row.id, $event)"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          size="small"
          link
          type="primary"
          @click="handleEdit(scope.$index, scope.row)"
        >
          编辑
        </el-button>
        <el-button
          size="small"
          link
          type="primary"
          @click="handleEdit(scope.$index, scope.row)"
        >
          设置sku
        </el-button>
        <el-popconfirm
          title="你确定要删除吗?"
          confirm-button-text="是"
          cancel-button-text="否"
          @confirm="confirmEvent(scope.row)"
          @cancel="cancelEvent"
        >
          <template #reference>
            <el-button size="small" type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper"
      :total="shopList.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <!-- 对话弹框 -->
  <el-dialog
    v-model="flag"
    :title="flags ? '添加商品' : '编辑商品'"
    :show-close="false"
    width="800"
  >
    <el-form
      style="max-width: 600px"
      :model="forms"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="forms.name" />
      </el-form-item>
      <el-form-item label="套装分类" prop="category">
        <el-select v-model="forms.category_id" placeholder="请选择商品分类">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品描述" prop="describe">
        <el-input v-model="forms.describe" />
      </el-form-item>

      <el-form-item label="商品主图片" name="image">
        <el-upload
          action="#"
          class="avatar-uploader"
          @change="uploadfil"
          :show-file-list="false"
          list-type="picture-card"
        >
          <img v-if="forms.img_path" :src="forms.img_path" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <!-- 商品轮播图 
          @change="uploadfil2"-->
      <el-form-item label="商品轮播图">
        <el-upload
          action="#"
          @change="uploadfil2"
          :file-list="FileList"
          list-type="picture-card"
          :auto-upload="false"
        >
          <el-icon><Plus /></el-icon>

          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <el-icon><zoom-in /></el-icon>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <el-icon><Download /></el-icon>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <el-form-item label="单价" prop="price">
        <el-input v-model="forms.price" />
      </el-form-item>
      <el-form-item label="库存" prop="repertory">
        <el-input v-model="forms.repertory" />
      </el-form-item>
      <el-form-item label="市场价格" prop="market">
        <el-input v-model="forms.market" />
      </el-form-item>
      <el-form-item label="销售" prop="sales_volume">
        <el-input v-model="forms.sales_volume" />
      </el-form-item>
      <el-form-item label="详情(富文本)">
        <QuillEditor
          style="width: 100%; height: 300px"
          contentType="html"
          toolbar="full"
          ref="quillRef"
          v-model:content="forms.content"
        />
      </el-form-item>
      <el-form-item label="规格">
        <div class="flex gap-2">
          <el-tag
            v-for="tag in forms.specification"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="w-20"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
          >
            + New Tag
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button v-if="flags" type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
        <el-button v-else type="primary" @click="updateForm(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, nextTick } from "vue";
import { Plus } from "@element-plus/icons-vue";
// import { ElInput } from 'element-plus'
import Breadcrumb from "../../components/bread/Breadcrumb.vue";
import { Quill } from "@vueup/vue-quill";
import {
  getShopListAPI,
  setDanGoodsAPI,
  setShangXinGoodsAPI,
  setJingXuanGoodsAPI,
  addShopListAPI,
  getBackAPI,
  updateShopAPI,
  delShopAPI,
} from "../../api/shoplist";

import { getShopCategoryListAPI } from "../../api/shopcategory";

// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

onMounted(async () => {
  getShopListDate();
  getCategory();
});

// 刷新列表
const render = () => {
  getShopListDate();
};

const getShopListDate = async () => {
  //获取列表数据
  let res = await getShopListAPI();
  shopList.value = Object.values(res.data.data);
  console.log(shopList.value);
};
// 获取分类
const getCategory = async () => {
  let ress = await getShopCategoryListAPI();
  categoryList.value = Object.values(ress.data.data);
  console.log(categoryList.value);
};

const shopList = ref([]);
const categoryList = ref([]);

const flag = ref(false); //控制弹窗显隐
const flags = ref(true); //控制添加、修改
const forms = ref({
  category_id: "", //分类id
  name: "", //商品名称
  describe: "", //描述
  img_arr: [], //轮播图
  img_path: "", //商品图
  price: "", //单价
  repertory: "", //库存
  market: "", //市场价格
  sales_volume: "", //销售
  content: "", //详情富文本
  specification: [], //规格
});

// 规格
const inputValue = ref("");
const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"]);
const inputVisible = ref(false);
const InputRef = ref();

const handleClose = (tag: string) => {
  forms.value.specification.splice(forms.value.specification.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    forms.value.specification.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

// 轮播图上传
const fileList = ref([
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
]);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const oid = ref(0);
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// 富文本
const content = ref([]);
const quillRef = ref<any>(null);

// 图片上传
let imageUrl = ref("");
let imageUrl2 = ref("");
let uploadfil = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file.raw);
    reader.onload = function () {
      imgResult = reader.result;
      forms.value.img_path = imgResult;
    };
  });
};

const FileList = ref([]);
// 多图上传
let uploadfil2 = (file) => {
  console.log(file);
  // return new Promise((resolve, reject) => {
  const reader = new FileReader();
  let imgResult = "";
  reader.readAsDataURL(file.raw);
  reader.onload = function () {
    imgResult = reader.result;
    forms.value.img_arr.push(imgResult);
  };
  // });
};

// 点击添加按钮
const setFlag = () => {
  flags.value = true; //控制标题等主题为添加
  flag.value = true; //控制弹窗显示
  reforms();
  forms.value.content = " ";
  FileList.value = [];
};
// 点击编辑按钮
const handleEdit = async (index, row) => {
  flags.value = false; //控制标题等主题为修改
  flag.value = true; //控制弹窗显示
  oid.value = row.id;
  // 回显
  let res = await getBackAPI(row.id);
  forms.value = res.data.data;
  forms.value.specification = Object.values(res.data.data.specification);
  FileList.value = Object.values(res.data.data.img_arr).map((item) => {
    return {
      name: +new Date(),
      url: item,
    };
  });
};

// 添加弹窗确定
const submitForm = async (formEl) => {
  flag.value = false; //控制弹窗隐藏
  console.log(forms.value);
  let res = await addShopListAPI(forms.value);
  if (res) {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
  }
  render();
};
// 编辑弹窗确定
const updateForm = async (formEl) => {
  flag.value = false; //控制弹窗隐藏
  console.log(forms.value);
  let res = await updateShopAPI(oid.value, forms.value);
  if (res) {
    ElMessage({
      message: "编辑成功",
      type: "success",
    });
  }
  render();
};
// 添加/编辑弹窗取消
const resetForm = (formEl) => {
  flag.value = false; //控制弹窗隐藏
};
// 删除商品
const confirmEvent = async (row) => {
  let res = await delShopAPI(row.id);
  if (res) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
  }
  render();
};
const cancelEvent = () => {
  //点击取消不删除
  console.log("cancel!");
};
// 数据回显归空
const reforms = () => {
  forms.value = {
    category_id: "", //分类id
    name: "", //商品名称
    describe: "", //描述
    img_arr: [], //轮播图
    img_path: "", //商品图
    price: "", //单价
    repertory: "", //库存
    market: "", //市场价格
    sales_volume: "", //销售
    content: "", //详情富文本
    specification: [], //属性
  };
};
// switch开关
const setDan = async (id, event) => {
  await setDanGoodsAPI(id, event);
};
const setShangXin = async (id, event) => {
  await setShangXinGoodsAPI(id, event);
};
const setJingXuan = async (id, event) => {
  await setJingXuanGoodsAPI(id, event);
};
</script>
<style scoped lang="less">
.avatar {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}
</style>